﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows;

namespace CPlatePrintSys.Annotation.Controls
{
    public static class ToggleButtonGroupBehavior
    {
        public static string GetGroupName(DependencyObject obj) => (string)obj.GetValue(GroupNameProperty);
        public static void SetGroupName(DependencyObject obj, string value) => obj.SetValue(GroupNameProperty, value);

        public static readonly DependencyProperty GroupNameProperty =
            DependencyProperty.RegisterAttached("GroupName", typeof(string), typeof(ToggleButtonGroupBehavior),
                new PropertyMetadata(null, OnGroupNameChanged));

        private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is ToggleButton toggleButton)
            {
                toggleButton.Checked += (s, args) =>
                {
                    var groupName = GetGroupName(toggleButton);
                    if (string.IsNullOrEmpty(groupName)) return;

                    var parent = VisualTreeHelper.GetParent(toggleButton) as DependencyObject;
                    if (parent == null) return;

                    foreach (var child in FindVisualChildren<ToggleButton>(parent))
                    {
                        if (child != toggleButton && GetGroupName(child) == groupName)
                            child.IsChecked = false;
                    }
                };
            }
        }

        private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj == null) yield break;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                var child = VisualTreeHelper.GetChild(depObj, i);
                if (child is T t) yield return t;
                foreach (var childOfChild in FindVisualChildren<T>(child))
                    yield return childOfChild;
            }
        }
    }
}
